package com.maolong.delayedprod.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.maolong.delayedprod.domain.Order;
import com.maolong.delayedprod.domain.Storage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Correlation;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class PayService {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    IOrderService orderService;
    @Autowired
    IStorageService storageService;

    @Transactional
    public void creatOrder(Order order){
        //往数据库里添加信息
        String name=order.getName(); //获取商品的名称
        boolean save = orderService.save(order);
//        int i=1/0;
        //库存扣减
        UpdateWrapper<Storage> wrapper = new UpdateWrapper<>();
        wrapper.eq("name",name);
        wrapper.setSql("count=count-1");
        storageService.update(wrapper);

        CorrelationData correlationData=new CorrelationData(order.getId().toString());
        MessagePostProcessor processor=message -> {
            message.getMessageProperties().setDelay(15000);
            message.getMessageProperties().setHeader("x-delay", 15000);
            return message;
        };

        //往延时队列里添加信息
        rabbitTemplate.convertAndSend("delayed_exchange","fail.error",order.getId(),processor,correlationData);
    }

    public void payOrder(Long id){
        log.info("要支付的订单号为：{}",id);
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("id", id));
        if("no".equals(order.getStatus())){
            order.setStatus("yes");
            orderService.updateById(order);
            log.info("支付成功");
        }else
            log.info("订单状态为yes，已经支付，无需再次支付");

    }
}
